<template>
  <div class="map-main">
    <img src="@/assets/images/dataCentre/recruitmentProgress/allmap.png" class="all-map" v-if="navInfo.navIndex===0">
    <img src="@/assets/images/dataCentre/recruitmentProgress/zhongguo.png" class="all-map" v-if="navInfo.navIndex===1&&navInfo.checkNav[1].value==='中国'">
    <img src="@/assets/images/dataCentre/recruitmentProgress/xinjiapo.png" class="xinjiapo-map" v-if="navInfo.navIndex===1&&navInfo.checkNav[1].value==='新加坡'">
    <div class="map-content" id="map" :class="{hiddenMap:navInfo.navIndex!==2}"></div>
  </div>
</template>

<script lang="ts" setup>
import {onMounted, watch, ref, onUnmounted} from "vue";
import * as echarts from 'echarts';
import {useMessage} from "@/hooks/web/useMessage";
import anHui from "./geoJsonData/anhui.json";
import shangHai from "./geoJsonData/shanghai.json";
import jiangSu from "./geoJsonData/jiangsu.json";
import zheJiang from "./geoJsonData/zhejiang.json";
import guangDong from "./geoJsonData/guangdong.json";
import siChuan from "./geoJsonData/sichuan.json";
import chongQing from "./geoJsonData/chongqing.json";
import {useDebounceFn} from "@vueuse/core";

const props = defineProps({
  navInfo:{
    type:Object,
    default:{
      navIndex:0,
      checkNav:[]
    }
  }
})

const emit = defineEmits(["selectRegion"])

const watchObj = watch(
  () =>props.navInfo.checkNav,(value) => {initMap()},{deep: true}
)

onMounted(()=>{
  const chartDom = document.getElementById('map');
  myChart.value = echarts.init(chartDom);
  initMap()
  window.addEventListener("resize",resizeFn)
})

onUnmounted(()=>{
  watchObj()
  window.removeEventListener("resize",resizeFn)
})

// 标记当前选中区域的名称
const selectName = ref("")

// 地图实例
const myChart = ref({})

/**
 * 地图重置大小
 */
const resizeFn = useDebounceFn(()=>{
  myChart.value.resize()
},200)

// 地图的GeoJson地址、可用地区等信息配置对象
const mapConfiguration = {
  anhui:{
    name:"安徽省",
    address:anHui,
    availabilityZone:["合肥市","安庆市","芜湖市","马鞍山市"],
    availabilityZoneValue:["合肥","安庆","芜湖","马鞍山"]
  },
  shanghai:{
    name:"上海",
    address:shangHai,
    availabilityZone:["上海市"],
    availabilityZoneValue:["上海"]
  },
  jiangsu:{
    name:"江苏省",
    address:jiangSu,
    availabilityZone:["南京市"],
    availabilityZoneValue:["南京"]
  },
  zhejiang:{
    name:"浙江省",
    address:zheJiang,
    availabilityZone:["杭州市"],
    availabilityZoneValue:["杭州"]
  },
  guangdong:{
    name:"广东省",
    address:guangDong,
    availabilityZone:["深圳市"],
    availabilityZoneValue:["深圳"]
  },
  sichuan:{
    name:"四川省",
    address:siChuan,
    availabilityZone:["成都市"],
    availabilityZoneValue:["成都"]
  },
  chongqing:{
    name:"重庆",
    address:chongQing,
    availabilityZone:["重庆市"],
    availabilityZoneValue:["重庆"]
  }
}

/**
 * 获取当前加载地图的GeoJson地址
 */
const getGeoJsonAddress = ()=>{
  const theNameOfTheRegion = props.navInfo.checkNav[2]?.value || "安徽省"
  switch (theNameOfTheRegion) {
    case "安徽省":
      return mapConfiguration.anhui;
    case "上海":
      return mapConfiguration.shanghai;
    case "江苏省":
      return mapConfiguration.jiangsu;
    case "浙江省":
      return mapConfiguration.zhejiang;
    case "广东省":
      return mapConfiguration.guangdong;
    case "四川省":
      return mapConfiguration.sichuan;
    case "重庆":
      return mapConfiguration.chongqing;
  }
}

// 地图点击防抖计时器
let eventTime

/**
 * 初始化地图示例
 */
const initMap = ()=>{
  let geoJsonInfo = getGeoJsonAddress()
  if(!geoJsonInfo){
    const { createMessage } = useMessage()
    createMessage.error('当前地区没有地图数据');
    return
  }
  selectName.value = ""
  echarts.registerMap('selectRegion', geoJsonInfo.address);
  initMapConfig()
  myChart.value.off("click")
  myChart.value.on('click', (params)=>{
    if(eventTime){
      clearTimeout(eventTime)
    }
    // 地图点击防抖
    eventTime = setTimeout(()=>{
      // 事件触发时，params包含了点击的图表元素的信息
      if (params.componentType === 'series'&&params.seriesType === 'map') {
        const availabilityZoneList = getGeoJsonAddress().availabilityZone
        if(!availabilityZoneList.includes(params.name)||(params.name===selectName.value)){
          // 点击不可用地区或已选中地区，重新初始化地图，恢复之前的选中状态
          selectName.value = ""
          emit("selectRegion",{})
          return
        }else{
          // 点击可用地区，通知父组件加载该地区数据
          selectName.value = params.name
          props.navInfo.checkNav[2].children.forEach(item=>{
            if(item.value === params.data.value){
              emit("selectRegion",item)
            }
          })
        }
      }
    },200)
  });
}


/**
 * 初始化地图配置
 */
const initMapConfig = ()=>{
  myChart.value.clear()
  let geoJsonInfo = getGeoJsonAddress()
  const option = {
    geo: {
      zoom: 1,
      show: true,
      map: 'selectRegion',
      label: {
        normal: {
          show: false,
        },
        emphasis: {
          show: false,
        }
      },
      roam: false,
      itemStyle: {
        normal: {
          shadowColor: 'rgba(25,25,121,0.25)',
          shadowOffsetY: 6,
          shadowOffsetX: 6,
          shadowBlur: 4
        }
      }
    },
    series: [{
      type: 'map',
      map: 'selectRegion',
      zoom:1,
      data:[],
      selectedMode:'single',
      normal: {
        label: {
          show: false,
        }
      },
      emphasis: {
        label: {
          show: false,
        },
      },
      select:{
        label: {
          show: false,
        },
        itemStyle: {
          areaColor: '#CEE8FB',
        },
      },
      itemStyle: {
        normal: {
          areaColor: '#CEE8FB',
          borderColor: '#7CB8F7',
          borderWidth: 1,
        },
        emphasis: {
          areaColor: '#CEE8FB',
        }
      },
    }]
  };
  // 添加高亮可用地区
  geoJsonInfo.availabilityZone.forEach((item,index)=>{
    const highlightConfiguration = {
      name:item,
      selected:selectName.value===item,
      value:geoJsonInfo.availabilityZoneValue[index],
      itemStyle:{
        areaColor:"#57A5F9",
      },
      emphasis:{
        itemStyle:{
          areaColor: '#57A5F9',
          borderColor: '#FFFFFF',
          borderWidth: 3,
        },
        label:{
          show:true,
          color:"#1E3859"
        }
      },
      label:{
        show:true,
        color:"#1E3859",
        fontWeight:600,
        fontSize:14
      },
      select:{
        label:{
          show:true,
          color:"#1E3859"
        },
        itemStyle: {
          areaColor: '#57A5F9',
          borderColor: '#FFFFFF',
          borderWidth: 3,
        },
      },
    }
    option.series[0].data.push(highlightConfiguration)
  })
  myChart.value.setOption(option);
}
</script>

<style scoped lang="less">
.map-main{
  width: 100%;
  height: 100%;
  position: absolute;
  top: 0;
  left: 0;
  z-index: 1;
  .all-map{
    width: 50%;
    height: auto;
    position: absolute;
    left: 12.2%;
    top: 12%;
  }
  .xinjiapo-map{
    width: 44%;
    height: auto;
    position: absolute;
    left: 18%;
    top: 28%;
  }
  .hiddenMap{
    opacity: 0;
    position: absolute;
    z-index: -1;
  }
  .map-content{
    padding-top: 50px;
    box-sizing: border-box;
    width: 800px;
    height: 100%;
    margin-left: 20%;
  }
}
</style>
